package com.thread.synchronizedTest;

/**
 * TestAccount--bdqnPractice
 *
 * @author: Jovi
 * @createTime: 2019-03-29 17:51
 **/
public class TestAccount implements Runnable {

    private Account account = new Account();

    private void makeWithdraw(int amount) {

        synchronized (account) {
            //判断当前余额是否足够
            if (account.getBalance() >= amount) {
                System.out.println(Thread.currentThread().getName() + "准备取款");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                account.withDraw(amount);
                System.out.println(Thread.currentThread().getName() + "完成取款");
            } else {
                System.out.println(Thread.currentThread().getName() + "余额不足" + account.getBalance());
            }
        }
    }

    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            //取款
            makeWithdraw(100);
            if (account.getBalance() < 0) {
                System.out.println("账户透支");
            }
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
